<template>
  <div class="delivery-tasks">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">配送任务管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建配送任务
          </el-button>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="待配送" :value="stats.pending">
              <template #suffix>
                <span class="unit">单</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="配送中" :value="stats.delivering">
              <template #suffix>
                <span class="unit">单</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="今日完成" :value="stats.completed">
              <template #suffix>
                <span class="unit">单</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="异常" :value="stats.exception">
              <template #suffix>
                <span class="unit">单</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="任务编号">
          <el-input v-model="searchForm.taskNo" placeholder="请输入任务编号" clearable />
        </el-form-item>
        <el-form-item label="配送员">
          <el-select v-model="searchForm.deliveryMan" placeholder="请选择配送员" clearable filterable>
            <el-option label="张三" value="zhangsan" />
            <el-option label="李四" value="lisi" />
            <el-option label="王五" value="wangwu" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待配送" value="pending" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="异常" value="exception" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.deliveryDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="taskNo" label="任务编号" width="150" />
        <el-table-column prop="deliveryMan" label="配送员" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="orderCount" label="订单数" width="90" align="right" />
        <el-table-column prop="deliveryAddress" label="配送区域" width="180" />
        <el-table-column prop="status" label="任务状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planTime" label="计划配送时间" width="160" />
        <el-table-column prop="actualTime" label="实际完成时间" width="160">
          <template #default="{ row }">
            {{ row.actualTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="100" align="center">
          <template #default="{ row }">
            <el-progress :percentage="row.completionRate" :color="getProgressColor(row.completionRate)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button link type="primary" size="small" @click="handleTrack(row)">
              <el-icon><Position /></el-icon>
              追踪
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)" v-if="row.status === 'pending'">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleCancel(row)" v-if="row.status !== 'completed'">
              <el-icon><CircleClose /></el-icon>
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送员" prop="deliveryMan">
              <el-select v-model="formData.deliveryMan" placeholder="请选择配送员" filterable>
                <el-option label="张三" value="zhangsan" />
                <el-option label="李四" value="lisi" />
                <el-option label="王五" value="wangwu" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送时段" prop="deliveryTime">
              <el-time-picker
                v-model="formData.deliveryTime"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">订单选择</el-divider>
        <el-form-item label="关联订单" prop="orders">
          <el-select
            v-model="formData.orders"
            multiple
            placeholder="请选择订单"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in availableOrders"
              :key="item.id"
              :label="`${item.orderNo} - ${item.address}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送区域" prop="deliveryAddress">
              <el-input v-model="formData.deliveryAddress" placeholder="请输入配送区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送路线" prop="routeId">
              <el-select v-model="formData.routeId" placeholder="请选择配送路线">
                <el-option label="路线A" value="1" />
                <el-option label="路线B" value="2" />
                <el-option label="路线C" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Edit, Delete, View, Position, CircleClose
} from '@element-plus/icons-vue'

// 统计数据
const stats = reactive({
  pending: 25,
  delivering: 18,
  completed: 56,
  exception: 2
})

// 搜索表单
const searchForm = reactive({
  taskNo: '',
  deliveryMan: '',
  status: '',
  deliveryDate: null
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新建配送任务')
const formRef = ref(null)

// 可用订单列表
const availableOrders = ref([
  { id: 1, orderNo: 'ORD001', address: '北京市朝阳区xxx' },
  { id: 2, orderNo: 'ORD002', address: '北京市海淀区xxx' },
  { id: 3, orderNo: 'ORD003', address: '北京市东城区xxx' }
])

// 表单数据
const formData = reactive({
  deliveryMan: '',
  phone: '',
  deliveryDate: null,
  deliveryTime: null,
  orders: [],
  deliveryAddress: '',
  routeId: '',
  remark: ''
})

// 表单验证规则
const rules = {
  deliveryMan: [{ required: true, message: '请选择配送员', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  deliveryDate: [{ required: true, message: '请选择配送日期', trigger: 'change' }],
  orders: [{ required: true, message: '请选择关联订单', trigger: 'change' }]
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    delivering: 'primary',
    completed: 'success',
    cancelled: 'info',
    exception: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待配送',
    delivering: '配送中',
    completed: '已完成',
    cancelled: '已取消',
    exception: '异常'
  }
  return textMap[status] || status
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 加载数据
const loadData = () => {
  loading.value = true
  
  setTimeout(() => {
    tableData.value = [
      {
        id: 1,
        taskNo: 'DT2024010001',
        deliveryMan: '张三',
        phone: '13800138000',
        orderCount: 15,
        deliveryAddress: '北京市朝阳区',
        status: 'delivering',
        planTime: '2024-01-01 09:00:00',
        actualTime: null,
        completionRate: 60
      },
      {
        id: 2,
        taskNo: 'DT2024010002',
        deliveryMan: '李四',
        phone: '13900139000',
        orderCount: 20,
        deliveryAddress: '北京市海淀区',
        status: 'completed',
        planTime: '2024-01-01 10:00:00',
        actualTime: '2024-01-01 16:30:00',
        completionRate: 100
      }
    ]
    pagination.total = 2
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'deliveryDate' ? null : ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新建配送任务'
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  ElMessage.info(`查看配送任务: ${row.taskNo}`)
}

// 追踪
const handleTrack = (row) => {
  ElMessage.info(`追踪配送员: ${row.deliveryMan}`)
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑配送任务'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 取消任务
const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消该配送任务吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('已取消配送任务')
    loadData()
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogTitle.value === '新建配送任务' ? '创建成功' : '更新成功')
      dialogVisible.value = false
      loadData()
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 分页改变
const handleSizeChange = () => {
  loadData()
}

const handleCurrentChange = () => {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.delivery-tasks {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .stats-row {
    margin-bottom: 24px;

    .stat-card {
      :deep(.el-card__body) {
        padding: 20px;
      }

      .unit {
        font-size: 14px;
        color: #909399;
        margin-left: 4px;
      }
    }
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

